package com.hgy.linkedlist;

public class Josepfu {
    public static void main(String[] args) {

        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.showBoy();
        circleSingleLinkedList.countBoy(1,2,5);
    }
}

//环形的单向链表
class CircleSingleLinkedList{
    private Boy first = null;

    //添加nums个Boy
    public void addBoy(int nums){
        if (nums < 1){
            System.out.println("nums的值不正确");
            return;
        }
        Boy curBoy = null;
        for (int i = 1; i <= nums ; i++) {
            Boy boy = new Boy(i);
            if (i==1){
                first = boy;
                curBoy = boy;
                boy.setNext(boy);
            }else{
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy = boy;
            }
        }
    }

    //遍历当前环形链表
    public void showBoy(){
        if (first == null){
            System.out.println("没有任何小孩");
            return;
        }
        Boy temp = first;
        do {
            System.out.printf("小孩的编号%d\n", temp.getNo());
            temp = temp.getNext();
        } while (temp!=first);
    }

    //根据用户的输入，计算出小孩出圈的顺序

    /**
     *
     * @param startNo       表示从第几个小孩开始数数
     * @param countNum  表示数几下
     * @param nums      表示最初有几个小孩
     */
    public void countBoy(int startNo, int countNum, int nums){
        if (first == null || startNo<1 || startNo >nums){
            System.out.println("参数输入有误，请重新输入！");
            return;
        }
        for (int j = 0; j < startNo - 1; j++) {
            first = first.getNext();
        }
        while (first!=first.getNext()){
            for (int j = 0; j < countNum - 2; j++) {
                first = first.getNext();
            }
            System.out.printf("第%d个小孩出圈\n", first.getNext().getNo());
            Boy temp = first;
            first = first.getNext().getNext();
            temp.setNext(first);
        }
        System.out.printf("最后剩下的小孩%d\n",first.getNo());
    }
}

//Boy类，表示一个节点
class Boy{
    private int no;
    private Boy next;

    public Boy(){}

    public Boy(int no){
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }
}